/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
// import QS from 'qs';
// import store from '../store/index'
import requestConfig from './config'
import Cookies from 'js-cookie'
import store from '../store/index'
import {Message} from 'element-ui'

/*
* 示例：一般假设API配置区分开发环境，测试环境，预上线环境，生产环境等
* API_CONFIG的属性值需与config下的env.conf对应，除development之外
*/
// const API_CONFIG = {
//   'development':'http://127.0.0.1:9001/api'
//   'production':"http://39.97.216.150/api",
// }

axios.defaults.baseURL = requestConfig[process.env.NODE_ENV].api

// 请求超时时间
// axios.defaults.timeout = 1000000;

// post请求头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';


// 请求拦截器
axios.interceptors.request.use(
    config => {
        config.headers['X-CSRFToken'] = Cookies.get('csrftoken')
        if (config.data instanceof FormData) {
            config.headers['Content-Type'] = 'multipart/form-data';
        } else {
            config.headers['Content-Type'] = 'application/json';
        }
        config.headers['Access-Control-Allow-Origin'] = '*';
        store.commit('setting/setRequestPercent', 50)
        return config;
    },
    error => {
        return Promise.error(error);
    }
)
axios.create({
    withCredentials: true // 允许携带cookie
});
// 响应拦截器
axios.interceptors.response.use(
    response => {
        store.commit('setting/setRequestPercent', 90)
        if (response.status === 200) {
            return Promise.resolve(response);
        }else{
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是200的情况
    error => {
      store.commit('setting/setRequestPercent', 0)
      console.error(error)
      if(error.response && error.response.status === 403) {
        location.href = requestConfig[process.env.NODE_ENV].loginPage
      }
    }
);
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params){
    store.commit('setting/setRequestPercent', 0)
    return new Promise((resolve, reject) =>{
        store.commit('setting/setRequestPercent', 10)
        axios.create({
            withCredentials: true,
    }).get(url, {
            params: params
        })
        .then(res => {
            store.commit('setting/setRequestPercent', 100)
            if(res.data.error_code == 0) {
                resolve(res.data);
            }else{
                switch(res.data.error_code) {
                    case 1001:
                    case 1002:
                    case 1003:
                    case 1004:
                    case 1005:
                    default:
                        Message.warning(res.data.message)
                    break;
                }
                reject(res.data)
            }
        })
        .catch(err => {
            store.commit('setting/setRequestPercent', 0)
            reject(err.data)
        })
    });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
    store.commit('setting/setRequestPercent', 0)
    url = url + '/'
    return new Promise((resolve, reject) => {
        store.commit('setting/setRequestPercent', 10)
        axios.create({
            withCredentials: true,
    }).post(url, params,
            {
                headers: {
                    'X-CSRFToken' : Cookies.get('csrftoken')
                }
            })
        .then(res => {
            store.commit('setting/setRequestPercent', 100)
            if(res.data.error_code == 0) {
                resolve(res.data);
            }else{
                switch(res.data.error_code) {
                    case 1001:
                    case 1002:
                    case 1003:
                    case 1004:
                    case 1005:
                    default:
                        Message.warning(res.data.message)
                    break;
                }
                reject(res.data)
            }
        })
        .catch(err => {
            store.commit('setting/setRequestPercent', 0)
            reject(err.data)
        })
    });
}

export default {
    axios: axios
};

export function upload(url, formData) {
    url = url + '/'
    return new Promise((resolve, reject) => {
        axios.create({
            withCredentials: true,
    }).post(url, formData,
             {
                headers: {
                    'X-CSRFToken' : Cookies.get('csrftoken')
                }
            })
        .then(res => {
            store.commit('setting/setRequestPercent', 100)
            if(res.data.error_code == 0) {
                resolve(res.data);
            }else{
                switch(res.data.error_code) {
                    case 1001:
                    case 1002:
                    case 1003:
                    case 1004:
                    case 1005:
                    default:
                        Message.warning(res.data.message)
                    break;
                }
                reject(res.data)
            }
        })
        .catch(err => {
            store.commit('setting/setRequestPercent', 100)
            console.log(err)
            reject(err.data)
        })
    });
}